<template>
  <div>
    <h3>登录页面</h3>
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" style="width:600px;margin:0 auto">
        <el-form-item label="用户名" prop="username">
    <el-input  v-model="ruleForm.username" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
    </el-form-item>
  
  <el-form-item>
    <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
    <button @click="showGoods(id)">跳转</button>
    <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
  </el-form-item>
</el-form>

  </div>
</template>

<script>
import axios from "axios"
  export default {
    data() {
      var validateUseename = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('用户名不能为空'));
        }
        const userRules=/^[a-zA-Z][0-9A-Za-z]{4,16}$/
        if(userRules.test(value)){
            return callback()
        }else{
           return callback(new Error('用户名不符合规则'));
        }
      };
      var validatePassword = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } 
        const passRules=/^[a-zA-Z][0-9a-zA-Z]{4,16}$/
        if(passRules.test(value)){
           return callback()
        }else{
             return callback(new Error('密码不符合规则'));
        }
      };
      return {
        ruleForm: {
          username:"",
          password: '',

        },
        rules: {
          password: [
            { validator: validatePassword, trigger: 'blur' }
          ],
          username: [
            { validator: validateUseename, trigger: 'blur' }
          ],
        }
      };
    },
    methods: {
        showGoods(id){
            //转跳到一类商品页面，并传递类别id
            this.$router.push({name:'Goods',params:{K_id:id}})
        },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            axios.post('http://127.0.0.1:8000/users/login/',this.ruleForm)
            .then(resp=>{
                console.log(resp);
                this.$router.push({name:'Name',params:{u_id:resp.data.user}})
                // this.$router.push('/name')
            })
            .catch(err=>{
                console.log(err);
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  }
</script>

<style>

</style>